<?php
declare (strict_types = 1);

namespace app\middleware;

use app\model\User;
use think\facade\Cache;
use think\facade\View;
use think\Response;

//全局过滤器
class MainFilter
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return \think\Response
     */
    public function handle($request, \Closure $next)
    {
        //echo 'MainFilter:before | ';
        //$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $shareId = $request->get('shareId');
        if ($shareId) {
            $userModel = new User();
            $shareUser = $userModel->where('id', $shareId)->find();
            if ($shareUser) {
                session('shareId', $shareId);
                View::assign('shareUser', $shareUser);
            }
        }


        //查询菜单
        $menuModel = new \app\model\Menu();
        $topMenuList = $menuModel
            ->where('pid', '0')
            ->where('is_delete', '0')
            ->order('rank')->select();
        View::assign('topMenuList', $topMenuList);

        //查询字典
        $name = '基础信息';
        $key = '网站名称';
        $rs = \think\facade\Db::query('select * from sys_dict_item a left join sys_dict b on a.dict_id=b.id where b.name=:name and a.name=:key',
            ['name'=>$name,'key'=>$key]);
        if (count($rs) > 0) {
            View::assign('sitename', $rs[0]['value']);
        }

        View::assign('tongji', $this->dict('基础信息','统计分析代码')[0]['value']);


        //生成随机数
        View::assign("r",rand(1,9999));

        $response = $next($request);
        //echo 'MainFilter:after | ';
        $content = $response->getContent();


        return $response;
    }

    public function dict($name, $key)
    {
        $rs = \think\facade\Db::query('select * from sys_dict_item a left join sys_dict b on a.dict_id=b.id where b.name=:name and a.name=:key',
            ['name'=>$name,'key'=>$key]);
        return $rs;
    }
}
